<template>
  <div>
    <div>
      <h3>路由</h3>
      <router-link v-for="(item, index) in userRoutes" :to="item.path" :key="index" style="margin-right: 10px">
        {{item.name}}
      </router-link>
    </div>
    <br/>
    <el-button @click="addRoute" type="primary">新增动态路由</el-button>
    <el-button @click="removeRoute" type="primary">移除动态路由</el-button>
    <div>请打开控制台查看结果</div>
    <el-button @click="requestSomething" type="primary">测试异步请求</el-button>
    <el-button @click="asyncRequestSomething" type="primary">测试同步请求</el-button>
    <div>
      <router-view />
    </div>
  </div>
</template>

<script lang="ts">
import { computed, defineComponent, onMounted } from 'vue';
import router from '@/router';
import store from '@/store';

export default defineComponent({
  name: 'Home',
  components: {
  },
  // setup (props, context) {
  setup () {
    // 1. 定义需要的数据
    const userRoutes = computed(() => {
      return store.state.routes;
    });
    const newRoutesData = [
      {
        path: '/helloWorld',
        name: 'HelloWorld',
        component: 'HelloWorld'
      }, {
        path: '/myComponent',
        name: 'MyComponent',
        component: 'MyComponent'
      }
    ];
    // 2. 定义需要的方法
    const addRoute = () => {
      newRoutesData.forEach((item: any) => {
        const formatedRoute = {
          path: item.path,
          name: item.name,
          component: () => {
            return import('../components/' + item.component + '.vue');
            // return import('../components/MyComponent.vue');
          }
        };
        router.addRoute(formatedRoute);
        store.commit('LOGIN_USER_DATA', newRoutesData);
        console.log('增加route之后，routes = ', router.getRoutes());
      });
    };
    const removeRoute = () => {
      store.commit('REMOVE_USER_DATA');
      console.log('增加route之后，routes = ', router.getRoutes());
    };

    const getSomething = () => {
      return new Promise(resolve => {
        // 模拟1s后返回数据
        setTimeout(() => resolve(222), 1000);
      });
    };

    const requestSomething = () => {
      console.log('222设置了定时器，虽然222是第二个执行，但是最后才输出：');
      console.log(111);
      getSomething().then(res => console.log(res));
      console.log(333);
    };
    // 这个时候会输出 111，333，222

    // 如果想要等数据返回后再执行后面的代码，那么就要使用 async/await
    const asyncRequestSomething = async () => {
      console.log('222设置了定时器，但对输出222的函数设定了异步等待（async+wait），所以是按照顺序，等定时其输出222后才输出333：');
      console.log(111);
      // 这时something会等到异步请求的结果回来后才进行赋值，同时不会执行之后的代码
      const something = await getSomething();
      console.log(something);
      console.log(333);
    };
    // 这个时候会输出 111，222，333

    // 3. 页面挂载初始化
    onMounted(() => {
    //
    });
    // 4. 返回需要暴露给页面使用的数据和方法
    return {
      userRoutes,
      addRoute,
      removeRoute,
      requestSomething,
      asyncRequestSomething
    };
  }
});
</script>
